package com.example.wengwyue.patientapplication.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.example.wengwyue.patientapplication.network.UserApi;
import com.hospital.common.api.ObjectCallback;
import com.hospital.common.api.PublicKeyManager;
import com.hospital.common.api.SimpleCallback;
import com.hospital.common.api.model.ApiResult;
import com.hospital.common.api.model.Error;
import com.hospital.common.api.secure.AESKey;
import com.hospital.common.api.secure.SoftDog;
import com.hospital.common.ui.base.AbsFragment;
import com.hospital.common.util.PatternUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.UUID;
import java.util.regex.Pattern;

import okhttp3.Call;

/**
 * Created by lingquan(quan.ling@hotmail.com) on 16/4/14.
 */
public abstract class AbsVerifyPhoneFragment extends AbsFragment {
    Handler mHandler;
    int mRemainSecond;
    long mPhone;

    Runnable mRefreshTimeRunnable = new Runnable() {
        @Override
        public void run() {
            mRemainSecond -= 1;

            onTimeTick(mRemainSecond);

            if (mRemainSecond > 0) {
                mHandler.postDelayed(mRefreshTimeRunnable, 1000);
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHandler = new Handler();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        mHandler.removeCallbacks(mRefreshTimeRunnable);
    }


    protected void sendCode(int type, CharSequence phone) {
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(getActivity(), "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!PatternUtil.isMobile(phone.toString())) {
            Toast.makeText(getActivity(), "请输入正确手机号", Toast.LENGTH_SHORT).show();
            return;
        }

        mPhone = Long.valueOf(phone.toString());
        showLoadingDialog();
        UserApi.sendVerifyCode(phone, new StringCallback() {
            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();

                String code = null;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    code = jsonObject.getJSONObject("additional").getString("verificationCode");
                } catch (Exception e) {

                }

                onSendMsgSuccess(mPhone, code);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();

                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

        });
    }

    protected void verifyCode(int type, CharSequence code) {
        if (mPhone == 0) {
            Toast.makeText(getActivity(), "请验证手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(getActivity(), "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        getPublicKeyAndPreRegister(code.toString());
    }

    protected void onSendMsgSuccess(long phone, String code) {
        mRemainSecond = 61;         //倒计时
        mHandler.post(mRefreshTimeRunnable);
    }

    protected void onTimeTick(int remain) {

    }

    protected void onVerifyCodeSuccess(long phone, AESKey aesKey) {

    }

    private void getPublicKeyAndPreRegister(final String code) {
        if (!Pattern.matches("^\\d{6}$", code)) {
            Toast.makeText(getActivity(), "请输入6位验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        showLoadingDialog();
        PublicKeyManager.getRSAPubKey(new SimpleCallback<String>() {
            @Override
            public void success(String data) {
                String salt = UUID.randomUUID().toString();
                try {
                    JSONObject obj = new JSONObject();
                    try {
                        obj.put("userName", String.valueOf(mPhone));
                        obj.put("verificationCode", code);
                        obj.put("salt", salt);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    preregister(SoftDog.encodeRSA(obj.toString(), data), salt);
                } catch (Exception e) {
                    e.printStackTrace();

                    hideLoadingDialog();
                }
            }

            @Override
            public void failure(String error) {
                hideLoadingDialog();

                Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void preregister(String data, final String salt) {
        UserApi.preRegister(data, new ObjectCallback<Void>() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();

                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ApiResult<Void> response, int id) {
                hideLoadingDialog();

                Error error = response.error;
                if (error != null) {
                    if (!error.hasError) {
                        Toast.makeText(getActivity(), "验证成功", Toast.LENGTH_LONG).show();

                        onVerifyCodeSuccess(mPhone,  SoftDog.getAESKey(salt));
                    } else {
                        Toast.makeText(getActivity(), error.des, Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

}
